package com.haredot.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.haredot.oss.properties.OssProperties;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 *  由于 haredot-commons 模块中使用了 LogAspect 切面，且 指定了
 *      com.haredot.controller.LogController.*(..)
 *   该类 必须提供，否则 项目启动会失败！
 */
@RestController
public class PreviewController {

    private OssProperties ossProperties;

    private OSS ossClient;

    @Autowired
    public PreviewController(@Nullable OSS ossClient, OssProperties ossProperties) {
        Assert.notNull(ossClient, "OSS 对象不存在");
        this.ossClient = ossClient ;
        this.ossProperties = ossProperties ;
    }

    @GetMapping(value = "/preview", produces = MediaType.IMAGE_JPEG_VALUE)
    public HttpEntity<byte[]> preview(@RequestParam("path") String objectName,
                                      @RequestParam(value = "type", required = false, defaultValue = "attachment") String type) throws Exception {

        OSSObject object = ossClient.getObject(new GetObjectRequest(ossProperties.getBucketName(), objectName));
        // 获取 OSS 中对应的文件内容
        try(InputStream objectContent = object.getObjectContent()) {
            // 转成 byte[] 数组
            byte[] bytes = IOUtils.toByteArray(objectContent);
            // 截取获取原上传的文件名
            int index = objectName.lastIndexOf("/");
            String downloadName = objectName.substring(index + 37);
            // 对文件名(包含中文)进行URL编码
            String encode = URLEncoder.encode(downloadName, StandardCharsets.UTF_8);

            if (!"attachment".equals(type)) type = "inline";
            // 下载文件
            return ResponseEntity
                    .ok()
                    .header("Content-Disposition", type + ";filename=" + encode)
                    .body(bytes);
        }catch (Exception e){
            e.printStackTrace();
            throw  e;
        }
    }
}
